<script setup>
import { ref, onMounted, watch, defineProps ,defineEmits} from "vue";
import request from '@/api/request';
import { ElMessage } from 'element-plus';
// 定义事件
let emits = defineEmits(["ref-table"]);
// 接收父组件传递的编辑数据
let props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
});

// 表单数据
let unitConversion = ref({
    ...props.data,
  // 如果有初始数据则使用初始数据，否则默认1
  conversionRate: props.data.conversionRate ?? 1
});

let mainUnits = ref([]); // 存储所有主单位





const fetchMainUnits = async () => {
  try {
    const response = await request.get("/unitConversion/index", {
      params: { isMainUnit: 1, size: 100 }
    });
    mainUnits.value = response.data.records;
  } catch (error) {
    ElMessage.error("获取主单位失败");
  }
};












// 监听是否为主单位的变化
watch(
  () => unitConversion.value.isMainUnit,
  (newVal) => {
    // 当切换为"是"(主单位)时，强制转换率为1
    if (newVal === '1') {
      unitConversion.value.conversionRate = 1;
    }else {
      // 如果是非主单位，加载主单位列表
      fetchMainUnits();
    }
  },
  { 
    immediate: true  // 初始化时立即执行一次，确保初始状态正确
  }
);

let unitConversions = ref([])
let onSubmit = () => { 
     request({
        url: '/unitConversion/update',
        method: 'put',
        data: unitConversion.value
    }).then(res => {
         emits("ref-table")
    })
   
}
let loadMaterialManagement = ()=>[
    request.get('/unitConversion/index').then(res=>{
        unitConversions.value = res.data;
    })
]
loadMaterialManagement()


const radio1 = ref('1'); // 是否启用（1=是，2=否）

let num1 = ref(1)
let num2 = ref(5000)
const handleChange1 = (value=number) => {
  console.log(value)
}

let loadData = () => {
    request({
        url: '/unitConversion/index',
        method: 'get',
        params: {
            current: page.value.current,
            size: page.value.size,
            unitId: unitConversion.value.unitId,
            unitName: unitConversion.value.unitName
        }
    }).then(res => {
        page.value = res.data
    }).catch(err => {
        ElMessage.error('数据加载失败')
    })
}
</script>

<template>
  <div>
    <el-card>
      <template #header>
        <el-form 
          :model="unitConversion" 
          ref="form" 
          label-width="80px" 
          :inline="false" 
          size="normal" 
          class="card_wrap"
        >
          <el-form-item label="单位编码" class="c_item">
            
            <el-input 
              v-model="unitConversion.unitId" 
              disabled
              style="width: 800px;"
            ></el-input> 
          </el-form-item>
          
          <el-form-item label="单位名称" class="c_item">
            
            <el-input 
              v-model="unitConversion.unitName" 
              style="width: 800px"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="是否为主单位" class="c_item">
            
            <el-radio-group v-model="unitConversion.isMainUnit" >
              <el-radio :value="1" size="large">是</el-radio>
              <el-radio :value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
         <el-form-item 
        v-if="unitConversion.isMainUnit === '0'" 
        label="换算比例" 
        required
        class="c_item"
      >
        <el-input-number 
          v-model="unitConversion.conversionRate" 
          :min="0.01" 
          step="1" 
          placeholder="请输入换算比例"
        ></el-input-number>
      </el-form-item>
          
         <el-form-item 
        v-if="unitConversion.isMainUnit === '0'" 
        label="主单位" 
        required
      >
        <el-select 
          v-model="unitConversion.mainUnit" 
          placeholder="请选择主单位" 
          style="width: 300px;"
          clearable
          popper-append-to-body
        >
          <el-option 
            v-for="(unit, index) in mainUnits" 
            :key="index + '-' + unit.unitId"
            :value="unit.unitId" 
            :label="unit.unitName"
          ></el-option>
        </el-select>
      </el-form-item>
          
          
          <el-form-item label="是否启用" class="c_item">
            
            <el-radio-group v-model="unitConversion.status">
              <el-radio :value="1" size="large">是</el-radio>
              <el-radio :value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="备注" class="c_item_big">
            
            <el-input 
              v-model="unitConversion.SpecificationsAndModels" 
              placeholder="请输入内容" 
              style="width: 800px;height: 60px;"
            ></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="onSubmit">确定修改</el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
/* 保持原有样式不变 */
.c_item {
  flex: 1;
  margin: 0px 5px 15px 0;
  width: calc((100%-10px)/1);
  min-width: calc((100% - 10px)/1);
  max-width: calc((100% - 10px)/1);

  &:nth-child(3n) {
    margin-right: 0;
  }
}
.c_item_big {
  flex: 2;
  margin: 0px 5px 15px 0;
  width: calc((100%-10px)/1);
  min-width: calc((100% - 10px)/1);
  max-width: calc((100% - 10px)/1);

  &:nth-child(3n) {
    margin-right: 0;
  }
}
.card_wrap {
  width: 98%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
</style>
